﻿using System;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

[System.Serializable]
public class RecordItem
{
    public string version = "";
    public string date = "";
    public string change = "";
}

[System.Serializable]
public class Record
{
    public string version = "";
    public List <RecordItem > record;
}

[InitializeOnLoad]
public class Startup
{
    static Startup()
    {
#if !UNITY_EDITOR
        return;
#endif
        Startup obj = new Startup();
        string curVersion = obj.GetWbVersion();
        //http get unity package version
        string url="http://wbgui.oss-cn-hangzhou.aliyuncs.com/UniWb/wb/config.json";
        string config = obj.GetHttpResponse(url, 6000);
        var root = JsonUtility.FromJson<Record>(config);
        Debug.Log("Wb UnityPackage curVersion = "+ curVersion);
        if (root.version.CompareTo(curVersion) == 1)
        {
            Debug.Log("发现"+ root.version + "新版本Wb插件!");
            obj.ShowDownLoadDialog(root);
        }
    }
    public void ShowDownLoadDialog(Record root)
    {
        string prjPath = Directory.GetCurrentDirectory(); 
        if (EditorUtility.DisplayDialog(root.version + "版本Wb插件更新提示！", root.record[0].change, "更新", "跳过")) //显示对话框
        {
            string packageName = "DN_PLUGIN_UNITY_"+ root.version + ".unitypackage";
            string packageFile = prjPath + "/" + packageName;
            // delete download error package 
            System.IO.File.Delete(packageFile);
            DownLoadFile("http://wbgui.oss-cn-hangzhou.aliyuncs.com/UniWb/wb/" + packageName, packageFile, (status, progress, msg) =>
            {
                if (-1 != status)
                {
                    Run("WbPackage is downloading...", packageName, progress);
                    if (1 == status)
                    {
                        // download success open unitypackage file
                        System.Diagnostics.Process.Start(packageFile);
                    }
                }
            });
        } else { 
            Debug.Log("Wb插件不是最新，可能导致新功能无法使用请及时更新！");
            System.IO.File.WriteAllText(prjPath + "/Assets/Wb/version.txt", root.version);
        }
    }
    public void Run(string title, string desc, float progress)
    {
        EditorApplication.update = delegate ()
        {
            bool isCancel = EditorUtility.DisplayCancelableProgressBar(title, desc, progress);
            if (isCancel || progress >= 1)
            {
                EditorUtility.ClearProgressBar();
                EditorApplication.update = null;
            }
        };
    }
    public HTTPDownLoad DownLoadFile(string url, string savePath, Action<int, float, string> callback)
    {
        // download file
        HTTPDownLoad download = new HTTPDownLoad(url, savePath, 5000, callback);
        download.DownLoad();
        return download;
    }
    public string GetHttpResponse(string url, int Timeout)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.ContentType = "text/html;charset=UTF-8";
        request.UserAgent = null;
        request.Timeout = Timeout;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
        string retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
        myResponseStream.Close();

        return retString;
    }
    public string GetWbVersion() 
    {
        string curVersion = "1.0.0";
        string prjPath = Directory.GetCurrentDirectory(); 
        if(System.IO.File.Exists(prjPath+"/Assets/Wb/version.txt"))
        {
            curVersion = System.IO.File.ReadAllText(prjPath+"/Assets/Wb/version.txt");
        }
        return curVersion;
    }
}